// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.ui.cdc;

import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.connectivity.IConnectivityProperty;
import org.dengues.core.metadata.MetadataHelper;
import org.dengues.core.resource.DenguesProjectFactory;
import org.dengues.core.resource.WarehouseResourceFactory;
import org.dengues.model.project.CDCConnType;
import org.dengues.model.project.ConnPropertySetType;
import org.dengues.model.project.ProjectFactory;
import org.dengues.model.project.ProjectType;
import org.dengues.model.warehouse.MetadataType;
import org.dengues.ui.PropertiesUiUtils;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-5-4 qiang.zhang $
 * 
 */
public class CDCSettingDialog extends TitleAreaDialog {

    private ConnPropertySetType setType;

    private Composite container;

    private Composite propsComp;

    private Text connText;

    private ChangeDataCaptureManager manager;

    private Text nameText;

    /**
     * Qiang.Zhang.Adolf@gmail.com CDCSettingDialog constructor comment.
     * 
     * @param parentShell
     */
    public CDCSettingDialog(Shell parentShell, ConnPropertySetType setType) {
        super(parentShell);
        setShellStyle(getShellStyle() | SWT.RESIZE | SWT.DIALOG_TRIM);
        this.setType = setType;
        manager = new ChangeDataCaptureManager(setType);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.TitleAreaDialog#createDialogArea(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected Control createDialogArea(Composite parent) {
        container = (Composite) super.createDialogArea(parent);
        final Composite composite = new Composite(container, SWT.NONE);
        GridLayout gridLayout = new GridLayout(2, false);
        composite.setLayout(gridLayout);
        GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
        composite.setLayoutData(gridData);
        Label label = new Label(composite, SWT.NONE);
        label.setText("CDC Name: ");
        nameText = new Text(composite, SWT.BORDER);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        nameText.setLayoutData(gridData);
        label = new Label(composite, SWT.NONE);
        label.setText("CDC Connectivity: ");
        nameText.addModifyListener(new ModifyListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
             */
            public void modifyText(ModifyEvent e) {
                updateStatusMsg();
            }

        });
        Composite composite2 = new Composite(composite, SWT.NONE);
        gridLayout = new GridLayout(2, false);
        composite2.setLayout(gridLayout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        composite2.setLayoutData(gridData);
        connText = new Text(composite2, SWT.BORDER);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        connText.setLayoutData(gridData);
        connText.setEditable(false);
        if (setType != null) {
            connText.setText(manager.getConnName());
        }
        Button button = new Button(composite2, SWT.PUSH);
        button.setText("...");
        button.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                DenguesCorePlugin default1 = DenguesCorePlugin.getDefault();
                IConnectivityProperty res = default1.getWarehousePluginService().openSelectConnSetDialog(true);
                if (res != null) {
                    setType = MetadataHelper.getConnSetType(res);
                    manager = new ChangeDataCaptureManager(setType);
                    createPropertiesControl();
                    connText.setText(manager.getConnName());
                }
            }
        });

        Button createSub = new Button(container, SWT.PUSH);
        createSub.setText("Create Subscriber");
        createSub.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                ExecuteCDCSQLDialog dialog = new ExecuteCDCSQLDialog(getParentShell(), manager, manager.genCreateSysSubscriberSQL(),
                        false);
                dialog.open();
                if (dialog.isExec()) {
                    setMessage("create Subscriber table success!");
                } else {
                    setMessage("create Subscriber table failure.", Status.WARNING);
                }
                setErrorMessage(null);
                Button button = getButton(IDialogConstants.OK_ID);
                button.setEnabled(true);
            }

        });
        propsComp = new Composite(container, SWT.NONE);
        gridLayout = new GridLayout(2, false);
        propsComp.setLayout(gridLayout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        propsComp.setLayoutData(gridData);

        createPropertiesControl();
        return container;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected void createButtonsForButtonBar(Composite parent) {
        super.createButtonsForButtonBar(parent);
        updateStatusMsg();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "updateStatusMsg".
     */
    private void updateStatusMsg() {
        String text = nameText.getText();
        EList<CDCConnType> cdcConns = DenguesProjectFactory.getDenguesProject().getProjectType().getCdcConns();
        boolean exist = false;
        for (CDCConnType connType : cdcConns) {
            if (connType.getName().equals(text)) {
                exist = true;
                break;
            }
        }
        Button button = getButton(IDialogConstants.OK_ID);
        if (text == null || text.length() == 0) {
            setErrorMessage("CDC name can't be empty.");
        } else if (exist) {
            setErrorMessage("CDC name  already exsit.");
        } else {
            setErrorMessage("Need to create Subscriber table.");
        }
        button.setEnabled(false);

    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createPropertiesControl".
     */
    private void createPropertiesControl() {
        if (setType != null) {
            PropertiesUiUtils.createPropertiesControls(null, propsComp, setType);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.Dialog#okPressed()
     */
    @Override
    protected void okPressed() {
        CDCConnType cdcConn = ProjectFactory.eINSTANCE.createCDCConnType();
        cdcConn.setConnSet(setType);
        cdcConn.setId(WarehouseResourceFactory.getEMFId());
        cdcConn.setName(nameText.getText());
        cdcConn.setSbsTable(ChangeDataCaptureManager.SYS_TSUBSCRIBERS);
        setType.setCdcConn(cdcConn);
        MetadataType mtype = manager.genSysSubscriberEMF();
        cdcConn.getCdcTables().add(mtype);
        ProjectType projectType = DenguesProjectFactory.getDenguesProject().getProjectType();
        projectType.getCdcConns().add(cdcConn);
        WarehouseResourceFactory.save(projectType);
        super.okPressed();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
     */
    @Override
    protected void configureShell(Shell newShell) {
        super.configureShell(newShell);
        newShell.setSize(540, 510);
        newShell.setText("Change Data Capture Settings");
    }
}
